package com.ims.business.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Lists;
import com.ims.business.constant.BusCons;
import com.ims.business.model.CardCatalog;
import com.ims.business.model.Opinion;
import com.ims.business.model.Order;
import com.ims.business.model.ScollImage;
import com.ims.business.model.Token;
import com.ims.business.model.WechatUser;
import com.ims.business.service.CardCatalogService;
import com.ims.business.service.OpinionService;
import com.ims.business.service.OrderService;
import com.ims.business.service.ScollImageService;
import com.ims.business.service.WechatUserService;
import com.ims.business.util.ThirdApiUtil;
import com.ims.common.constant.IMSCons;
import com.ims.common.matatype.Dto;
import com.ims.common.matatype.Dtos;
import com.ims.common.support.pay.WxPay;
import com.ims.common.util.FileOperation;
import com.ims.common.util.IMSCxt;
import com.ims.common.util.IMSUtil;
import com.ims.common.util.JsonUtil;
import com.ims.common.util.R;
import com.ims.common.util.SqlHelpUtil;
import com.ims.common.util.XmlUtil;
import com.ims.system.constant.SystemCons;
import com.ims.system.util.CacheCxt;

/**
 * 
 * 类名:com.ims.business.controller.ApiController
 * 描述:api接口
 * 编写者:陈骑元
 * 创建时间:2019年7月13日 下午3:43:37
 * 修改说明:
 */
@Controller
@RequestMapping("/api")
public class ApiController {
	/**
	 * 日志类
	 */
	private static Log log = LogFactory.getLog(ApiController.class);
	@Autowired
    private ScollImageService scollImageService;
	@Autowired
    private OrderService orderService;
	@Autowired
	private CardCatalogService cardCatalogService;
	@Autowired
	private OpinionService opinionService;
	@Autowired
	private WechatUserService wechatUserService;
	
	/**
	 * 
	 * 简要说明：获取code认证信息
	 * 编写者：陈骑元
	 * 创建时间：2019年7月15日 上午8:56:52
	 * @param 说明
	 * @return 说明
	 */
	@PostMapping("getCodeAuth")
	@ResponseBody
	public R getCodeAuth(String code){
		if(IMSUtil.isEmpty(code)){
			
			return R.error("授权code参数不能为空");
		}
		String openid=ThirdApiUtil.getAppletOpenid(code);
		Token token=new Token();
		token.setOpenid(openid);
		return R.toData(token);
	}
	/**
	 * 
	 * 简要说明：保存用户信息
	 * 编写者：陈骑元
	 * 创建时间：2019年7月16日 上午12:01:34
	 * @param 说明
	 * @return 说明
	 */
	@PostMapping("saveWechatUser")
	@ResponseBody
	public R saveWechatUser(String openid,String nickname,String headimgurl,String sex){
		EntityWrapper<WechatUser> wrapper = new EntityWrapper<WechatUser>();
		SqlHelpUtil.eq(wrapper, "openid",openid);
		WechatUser wechatUser=wechatUserService.selectOne(wrapper);
		Date currentTime=IMSUtil.getDateTime();
		if(IMSUtil.isNotEmpty(wechatUser)){
		
			wechatUser.setNickname(nickname);
			wechatUser.setHeadPhotoUrl(headimgurl);
			wechatUser.setSex(sex);
			wechatUser.setUpdateTime(currentTime);
			wechatUserService.updateById(wechatUser);
		}else{
			wechatUser=new WechatUser();
			wechatUser.setOpenid(openid);
		    wechatUser.setNickname(nickname);
		    wechatUser.setHeadPhotoUrl(headimgurl);
		    wechatUser.setSex(sex);
		    wechatUser.setCreateTime(currentTime);
	     	wechatUser.setUpdateTime(currentTime);
	     	wechatUserService.insert(wechatUser);
		}
		return R.ok();
	}
	/**
	 * 显示图片
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "showImage")
	public void showImage(String fileName,HttpServletRequest request,HttpServletResponse response) {
		String folderPath=CacheCxt.getParamValue(BusCons.SAVE_ROOT_PATH_KEY	);
		String filePath=folderPath+File.separator+BusCons.SCOLL_IMAGE+File.separator+fileName;
		FileOperation.downloadFile(request, response,  filePath, fileName);
	}
	 /**
	  * 
	  * 简要说明：查询洗车卡
	  * 编写者：陈骑元
	  * 创建时间：2019年7月13日 下午3:44:43
	  * @param 说明
	  * @return 说明
	  */
	 @PostMapping("queryCardCatalogList")
	 @ResponseBody
     public R queryCardCatalogList(){
    	 Dto pDto=Dtos.newDto();
    	 pDto.put("status", SystemCons.ENABLED_YES);
    	 pDto.setOrder(" sort_no ASC ");
    	 List<CardCatalog> cardCatalogList=cardCatalogService.list(pDto);
    	 CacheCxt.convertDict(cardCatalogList);
    	 String telephone=CacheCxt.getParamValue(BusCons.TELEPHONE);
    	 return R.toList(cardCatalogList).put(BusCons.TELEPHONE,telephone);
     }
	 /**
	  * 
	  * 简要说明：查询审车年限
	  * 编写者：陈骑元
	  * 创建时间：2019年7月13日 下午3:44:43
	  * @param 说明
	  * @return 说明
	  */
	 @PostMapping("queryCarLimitList")
	 @ResponseBody
     public R queryCarLimitList(){
    	 List<Dto> dataList=Lists.newArrayList();
    	 Dto dataDtoIn=Dtos.newDto();
    	 dataDtoIn.put("carLimitValue", CacheCxt.getDictValue("car_limit", BusCons.CAR_LIMIT_SIX_IN	));
    	 dataDtoIn.put("carLimit", BusCons.CAR_LIMIT_SIX_IN);
    	 dataDtoIn.put("carLimitAmount", CacheCxt.getParamIntValue(BusCons.SIX_YEAR_IN_PRICE));
    	 dataList.add(dataDtoIn);
    	 Dto dataDtoUp=Dtos.newDto();
    	 dataDtoUp.put("carLimitValue", CacheCxt.getDictValue("car_limit", BusCons.CAR_LIMIT_SIX_UP));
    	 dataDtoUp.put("carLimit", BusCons.CAR_LIMIT_SIX_UP);
    	 dataDtoUp.put("carLimitAmount", CacheCxt.getParamIntValue(BusCons.SIX_YEAR_UP_PRICE));
    	 dataList.add(dataDtoUp);
    	 return R.toList(dataList);
     }
	 /**
	  * 
	  * 简要说明：查询轮播图片
	  * 编写者：陈骑元
	  * 创建时间：2019年7月13日 下午3:55:52
	  * @param 说明
	  * @return 说明
	  */
	 @PostMapping("queryScollImageList")
	 @ResponseBody
     public R queryScollImageList(){
    	 Dto pDto=Dtos.newDto();
    	 pDto.put("status", SystemCons.ENABLED_YES);
    	 pDto.setOrder(" sort_no ASC ");
    	 List<ScollImage> scollImageList=scollImageService.list(pDto);
    	 
    	 return R.toList(scollImageList);
     }
	 
	 /**
	  * 
	  * 简要说明：保存反馈意见
	  * 编写者：陈骑元
	  * 创建时间：2019年7月13日 下午9:09:06
	  * @param 说明
	  * @return 说明
	  */
	 @PostMapping("saveWashOrder")
	 @ResponseBody
	 public R saveWashOrder(Order order,String typeId,HttpServletRequest request){
		 String openid=order.getOpenid();
		 if(IMSUtil.isEmpty(order.getOpenid())){
			 
			 return R.error("微信的openid参数不能为空");
		 }
         if(IMSUtil.isEmpty(typeId)){
			 
			 return R.error("卡类型编号[typeId]参数不能为空");
		 }
         
         CardCatalog cardCatalog=cardCatalogService.selectById(typeId);
         if(IMSUtil.isEmpty(cardCatalog)){
        	 return R.error("卡类型编号[typeId]参数不合法");
         }
         int cardAumount=cardCatalog.getCardAmount();
         String ip=IMSCxt.getClientIpAddr(request);
         String orderId=CacheCxt.createOrderNum();
 		 String notifyUrl=CacheCxt.getParamValue(BusCons.WECHAT_NOTIFY_URL_KEY);
 		 R r=WxPay.pushWechatOrder(orderId, cardAumount*100,ip, notifyUrl, openid,"购买洗车卡");
 		 if(IMSCons.SUCCESS==r.getAppCode()	){
 			 order.setCardType(cardCatalog.getCardType());
 		     order.setOrderAmount(cardAumount+0d);
 		     order.setOrderType(BusCons.ORDER_TYPE_WASH);
 			 order.setOrderTime(IMSUtil.getDateTime());
 			 order.setOrderId(orderId);
 		     boolean result=orderService.insert(order);
 		     if(result){
 		    	 return r;
 		     }else{
 		    	 
 		    	 return R.error("购买洗车卡失败，订单信息无法保存");
 		     }
 	 		
 		 }
 		
 		 return r;
        
	 }
	 
	 /**
	  * 
	  * 简要说明：审核订单
	  * 编写者：陈骑元
	  * 创建时间：2019年7月13日 下午9:09:06
	  * @param 说明
	  * @return 说明
	  */
	 @PostMapping("saveAuditOrder")
	 @ResponseBody
	 public R saveAudithOrder(Order order,HttpServletRequest request){
		 String openid=order.getOpenid();
		 if(IMSUtil.isEmpty(order.getOpenid())){
			 
			 return R.error("微信的openid参数不能为空");
		 }
		 String carLimit=order.getCarLimit();
         if(IMSUtil.isEmpty(carLimit)){
        	 return R.error("车辆年限[carLimit]参数不能为空");
         }
         int aumount=0;
         if(BusCons.CAR_LIMIT_SIX_IN.equals(carLimit)){
        	 aumount=CacheCxt.getParamIntValue(BusCons.SIX_YEAR_IN_PRICE);
         }else{
        	 aumount=CacheCxt.getParamIntValue(BusCons.SIX_YEAR_UP_PRICE);
         }
       
         String ip=IMSCxt.getClientIpAddr(request);
         String orderId=CacheCxt.createOrderNum();
 		 String notifyUrl=CacheCxt.getParamValue(BusCons.WECHAT_NOTIFY_URL_KEY);
 		 R r=WxPay.pushWechatOrder(orderId, aumount*100,ip, notifyUrl, openid,"审车");
 		 order.setOrderAmount(aumount+0d);
	     order.setOrderType(BusCons.ORDER_TYPE_AUDIT);
	     order.setOrderTime(IMSUtil.getDateTime());
	     order.setOrderId(orderId);
	     boolean result=orderService.insert(order);
	     if(result){
	    	 return r;
	     }else{
	    	 
	    	 return R.error("订单信息无法保存");
	     }
        
	 }
	 /**
	  * 
	  * 简要说明：保存反馈意见
	  * 编写者：陈骑元
	  * 创建时间：2019年7月13日 下午9:09:06
	  * @param 说明
	  * @return 说明
	  */
	 @PostMapping("saveOpinion")
	 @ResponseBody
	 public R saveOpinion(Opinion opinion){
		 if(IMSUtil.isEmpty(opinion.getOpenid())){
			 
			 return R.error("微信的openid参数不能为空");
		 }
         if(IMSUtil.isEmpty(opinion.getOpinionContent())){
			 
			 return R.error("反馈内容不能为空");
		 }
         opinion.setCreateTime(IMSUtil.getDateTime());
         boolean result=opinionService.insert(opinion);
         if(result){
        	 
        	 return R.ok();
         }else{
        	 return R.error();
         }
	 }
	 /**
	  * 
	  * 简要说明：查询微信用户信息
	  * 编写者：陈骑元
	  * 创建时间：2019年7月14日 下午10:57:55
	  * @param 说明
	  * @return 说明
	  */
	 @PostMapping("queryWechatUser")
	 @ResponseBody
	 public R queryWechatUser(String openid){
		 if(IMSUtil.isEmpty(openid)){
			 
			 return R.error("微信openid参数不能为空");
			 
		 }
		 EntityWrapper<WechatUser> wrapper = new EntityWrapper<WechatUser>();
		 SqlHelpUtil.eq(wrapper, "openid",openid);
		 WechatUser wechatUser=wechatUserService.selectOne(wrapper);
		 return R.toData(wechatUser);
		 
	 }
	 /**
	  * 
	  * 简要说明：我的个人中心
	  * 编写者：陈骑元
	  * 创建时间：2019年7月16日 下午10:10:58
	  * @param 说明
	  * @return 说明
	  */
	 @PostMapping("queryMyCenter")
	 @ResponseBody
	 public R queryMyCenter(String openid){
		 if(IMSUtil.isEmpty(openid)){
			 
			 return R.error("微信openid不能为空");
		 }
		 EntityWrapper<WechatUser> wrapper = new EntityWrapper<WechatUser>();
		 SqlHelpUtil.eq(wrapper, "openid",openid);
		 WechatUser wechatUser=wechatUserService.selectOne(wrapper);
		 //查询洗车卡
		 EntityWrapper<Order> orderWrapper= new EntityWrapper<Order>();
		 SqlHelpUtil.eq(orderWrapper, "openid",openid);
		 SqlHelpUtil.eq(orderWrapper,"order_type", BusCons.ORDER_TYPE_WASH);
		 orderWrapper.ge("expire_time", IMSUtil.getCurrentDate());
		 orderWrapper.orderBy("expire_time",false);
		 Order order=orderService.selectOne(orderWrapper);
		 Dto dataDto=Dtos.newDto();
		 if(IMSUtil.isNotEmpty(order)){
			 dataDto.put("whetherCard", IMSCons.WHETHER_YES);
			 dataDto.put("expireTime",IMSUtil.date2String(order.getExpireTime(), IMSCons.DATE) );
		 }else{
			 dataDto.put("whetherCard", IMSCons.WHETHER_NO);
		 }
		 dataDto.put("nickname", wechatUser.getNickname());
		 dataDto.put("headPhotoUrl", wechatUser.getHeadPhotoUrl());
		 dataDto.put("whetherMember", wechatUser.getWhetherMember()	);
		 return R.toData(dataDto);
	 }
	 /**
		 * 
		 * 微信支付通知
		 * 
		 * @param request
		 * @param response
		 * @throws IOException
		 */
		@SuppressWarnings({ "unchecked", "rawtypes" })
		@RequestMapping(value = "wxPayNotify")
		public void wxPayNotify(HttpServletRequest request, HttpServletResponse response) {
			String returnMsg = getNodifyMsg(request);
			if(IMSUtil.isNotEmpty(returnMsg)){
				Map returnMap =XmlUtil.parseXml2Map(returnMsg);
				if(IMSUtil.isNotEmpty(returnMap)){
					Dto returnDto=Dtos.newDto();
					returnDto.putAll(returnMap);
					log.info("微信支付通知结果参数：" + JsonUtil.toJson(returnDto));
					String return_code = returnDto.getString("return_code");
					if ("SUCCESS".equals(return_code)) {
						String result_code=returnDto.getString("return_code");
						if ("SUCCESS".equals(result_code)) {
							String orderId = returnDto.getString("out_trade_no");
							Order order=orderService.selectById(orderId);
							if(IMSUtil.isNotEmpty(order)){
								Date currentTime=IMSUtil.getDateTime();
								order.setWhetherPay(IMSCons.WHETHER_YES);
								order.setPayTime(currentTime);
							
								if(BusCons.ORDER_TYPE_WASH.equals(order.getOrderType())){
									String cardType=order.getCardType();
									if(IMSUtil.isNotEmpty(cardType)){
										int cardTypeInt=Integer.parseInt(cardType);
										Date expireTime=IMSUtil.getDateMonth(cardTypeInt);
										order.setExpireTime(expireTime); //设置到期日期
										
									}
									String openid=order.getOpenid();
									EntityWrapper<WechatUser> wrapper = new EntityWrapper<WechatUser>();
									SqlHelpUtil.eq(wrapper, "openid",openid);
									WechatUser wechatUser=wechatUserService.selectOne(wrapper);
									if(IMSUtil.isNotEmpty(wechatUser)){
										wechatUser.setUsername(order.getUsername());
										wechatUser.setAreaName(order.getAreaName());
										wechatUser.setCarColor(order.getCarColor());
										wechatUser.setCarNum(order.getCarNum());
										wechatUser.setCarModel(order.getCarModel());
										wechatUser.setDetailAddress(order.getDetailAddress());
										wechatUser.setMobile(order.getMobile());
										wechatUser.setUpdateTime(currentTime);
										wechatUser.setWhetherMember(IMSCons.WHETHER_YES);
										wechatUserService.updateById(wechatUser);
									}else{
										wechatUser=new WechatUser();
										wechatUser.setOpenid(openid);
										wechatUser.setUsername(order.getUsername());
										wechatUser.setAreaName(order.getAreaName());
										wechatUser.setCarColor(order.getCarColor());
										wechatUser.setCarNum(order.getCarNum());
										wechatUser.setCarModel(order.getCarModel());
										wechatUser.setDetailAddress(order.getDetailAddress());
										wechatUser.setMobile(order.getMobile());
										wechatUser.setCreateTime(currentTime);
										wechatUser.setUpdateTime(currentTime);
										wechatUser.setWhetherMember(IMSCons.WHETHER_YES);
										wechatUserService.insert(wechatUser);
									}
								}
								orderService.updateById(order);
								log.info("订单号："+orderId+" 微信支付成功");
							}
							
						}
						
					}
					Dto successDto=Dtos.newDto();
					successDto.put("return_code", "SUCCESS");  
					successDto.put("return_msg", "OK"); 
					String  outString=XmlUtil.getDtoToXml(successDto);
					IMSCxt.writeRaw(response, outString);
				}
				
			}
			
		}
		/**
		 * 接收微信的异步通知
		 * 
		 * @throws IOException
		 */
		private String getNodifyMsg(HttpServletRequest request) {
			
			
			try {
				
				InputStream inputStream;
				StringBuffer sb = new StringBuffer();
				inputStream = request.getInputStream();
				String s;
				BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
				while ((s = in.readLine()) != null) {
					sb.append(s);
				}
				in.close();
				inputStream.close();
				return sb.toString();
			} catch (Exception e) {
				// TODO: handle exception
			}
			return "";
		}

} 
